package com.paobuji.aidebao.myapplication.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.paobuji.aidebao.myapplication.R;
import com.paobuji.aidebao.myapplication.activity.BaseActivity;
import com.paobuji.aidebao.myapplication.appinterface.GetInterfaceObjctListener;
import com.paobuji.aidebao.myapplication.bean.BluResult;
import com.paobuji.aidebao.myapplication.bean.UserBeanResult;
import com.paobuji.aidebao.myapplication.ble.utils.BluetoothController;
import com.paobuji.aidebao.myapplication.ble.utils.ConstantUtils;
import com.paobuji.aidebao.myapplication.ble.utils.Util;
import com.paobuji.aidebao.myapplication.tool.ACache;
import com.paobuji.aidebao.myapplication.tool.BluDataUtil;
import com.paobuji.aidebao.myapplication.video.OnTouchSport;
import com.paobuji.aidebao.myapplication.video.Video;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class VedioActivity extends BaseActivity {
    //    Video video;
    BluResult bluResult;
    BluDataUtil bluDataUtil = new BluDataUtil();

    public double sportDis;      //运动里程
    public String sportTime;     //运动时间
    public int sportCor;         //消耗卡路里

    boolean slopeFlag;
    float now_speed = 0;
    int now_slope = 0;
    float max_speed = 0;
    int max_slope = 0;
    float min_speed = 0;
    int bluState;

    Util u = new Util();
//
//    TextView sport_heart;
//    TextView sport_time;
//    TextView sport_kcor;
//    TextView sport_dis;
//    TextView sport_speed;
//    TextView sport_slope;
//    TextView btnText;
//    ImageButton stopBtn;
//
//    TextView two;
//    TextView four;
//    TextView six;
//    TextView eight;
//    TextView ten;
//    TextView travel;


    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_speed)
    TextView tv_speed;
    @BindView(R.id.tv_k)
    TextView tv_k;
    @BindView(R.id.tv_mileage)
    TextView tv_mileage;
    @BindView(R.id.iv_player)
    TextView iv_player;

    DecimalFormat decimalFormat;
    BluetoothController controller;

    MsgReceiver receiver;

    LinearLayout kuaijieLayout;

    int dataNum = 0;
    boolean flag = false;
    String model = null;
    ACache aCache;

    RelativeLayout ex_layout;
    TextView ex_tv;

    Handler x;
    boolean isStop = false;

    ImageView yindao;   //第一打开app的引导图片


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_vedio);
        ButterKnife.bind(this);
        aCache = ACache.get(this);
        x = new Handler();//定义一个handle对象
        //数据格式化
        decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        controller = BluetoothController.getInstance();
        initView();
        initBle();

        getModel();

//        isFirst();
    }

    @OnClick({R.id.iv_remove, R.id.iv_3, R.id.iv_6, R.id.iv_add, R.id.iv_stop, R.id.iv_player, R.id.tv_left})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_remove:
                onSetSpeed(-1);
                break;
            case R.id.iv_add:
                onSetSpeed(1);
                break;
            case R.id.iv_player:

                if (bluState == 10) {

                    startSport();
                    iv_player.setText(R.string.stop);
                } else if (bluState == 20) {
                    Log.i("蓝牙", "退出7");
                    stopSport();
                    iv_player.setText(R.string.startRun);

                }
                break;
            case R.id.iv_stop:


                stopSport();
                break;
            case R.id.iv_3:
                controller.write(bluDataUtil.addSpeed(decimalFormat.format(3)));  //速度调节

                break;
            case R.id.iv_6:
                controller.write(bluDataUtil.addSpeed(decimalFormat.format(6)));  //速度调节
                break;
            case R.id.tv_left:
                finish();
                break;
        }
    }

//
//    @Override
//    public void onClick(View view) {
//        switch (view.getId()) {
//            case R.id.sport_speed:
//                if (kuaijieLayout.getVisibility() == View.GONE) {
//                    kuaijieLayout.setVisibility(View.VISIBLE);
//                    n = 1;
//                }
//                break;
//            case R.id.sport_slope:
//                if (kuaijieLayout.getVisibility() == View.GONE) {
//                    kuaijieLayout.setVisibility(View.VISIBLE);
//                    n = 2;
//                }
//                break;
//            case R.id.stopBtn:
//                if (bluState == 10) {
//
//                    startSport();
//                } else if (bluState == 20) {
//                    Log.i("蓝牙", "退出7");
//                    stopSport();
//                }
//
//                break;
//            case R.id.two:
//                if (n == 1) {    //速度
//                    controller.write(bluDataUtil.addSpeed(decimalFormat.format(2)));  //速度调节
//                } else if (n == 2) {  //坡度
//                    controller.write(bluDataUtil.addSlope(String.valueOf(2)));   //坡度
//                }
//                kuaijieLayout.setVisibility(View.GONE);
//                break;
//            case R.id.four:
//                if (n == 1) {    //速度
//                    controller.write(bluDataUtil.addSpeed(decimalFormat.format(4)));  //速度调节
//                } else if (n == 2) {  //坡度
//                    controller.write(bluDataUtil.addSlope(String.valueOf(4)));   //坡度
//                }
//                kuaijieLayout.setVisibility(View.GONE);
//                break;
//            case R.id.six:
//                if (n == 1) {    //速度
//                    controller.write(bluDataUtil.addSpeed(decimalFormat.format(6)));  //速度调节
//                } else if (n == 2) {  //坡度
//                    controller.write(bluDataUtil.addSlope(String.valueOf(6)));   //坡度
//                }
//                kuaijieLayout.setVisibility(View.GONE);
//                break;
//            case R.id.eight:
//                if (n == 1) {    //速度
//                    if (8 <= max_speed) {
//                        controller.write(bluDataUtil.addSpeed(decimalFormat.format(8)));  //速度调节
//                    } else {
//                        toastLog("您不能超多最大速度");
//                    }
//
//                } else if (n == 2) {  //坡度
//                    if (8 <= max_slope) {
//                        controller.write(bluDataUtil.addSlope(String.valueOf(8)));   //坡度
//                    } else {
//                        toastLog("您不能超多最大坡度");
//                    }
//                }
//                kuaijieLayout.setVisibility(View.GONE);
//                break;
//            case R.id.ten:
//                if (n == 1) {    //速度
//                    if (10 <= max_speed) {
//                        controller.write(bluDataUtil.addSpeed(decimalFormat.format(10)));  //速度调节
//                    } else {
//                        toastLog("您不能超多最大速度");
//                    }
//                } else if (n == 2) {  //坡度
//                    if (10 <= max_slope) {
//                        controller.write(bluDataUtil.addSlope(String.valueOf(10)));   //坡度
//                    } else {
//                        toastLog("您不能超多最大坡度");
//                    }
//                }
//                kuaijieLayout.setVisibility(View.GONE);
//                break;
//            case R.id.travel:
//                if (n == 1) {    //速度
//                    if (12 <= max_speed) {
//                        controller.write(bluDataUtil.addSpeed(decimalFormat.format(12)));  //速度调节
//                    } else {
//                        toastLog("您不能超多最大速度");
//                    }
//                } else if (n == 2) {  //坡度
//                    if (12 <= max_slope) {
//                        controller.write(bluDataUtil.addSlope(String.valueOf(12)));   //坡度
//                    } else {
//                        toastLog("您不能超多最大坡度");
//                    }
//                }
//                kuaijieLayout.setVisibility(View.GONE);
//                break;
//
//            case R.id.yindao:
//                yindao.setVisibility(View.GONE);
//                break;
//        }
//    }

    public void isFirst() {
        if (aCache.getAsString("isfirst") == null || "".equals(aCache.getAsString("isfirst"))) {
            yindao.setVisibility(View.VISIBLE);
        } else {
            yindao.setVisibility(View.GONE);
            aCache.put("isfirst", "false");
        }
    }

    //正常停止
    public void stopSport() {
        controller.write(bluDataUtil.startStop("0"));         //停止，由运动状态到停止状态
//        video.stop();
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }

        //跳转到结果页面
        Intent intent = new Intent(VedioActivity.this, FinishSportActivity.class);
        intent.putExtra("sportDis", sportDis);
        intent.putExtra("sportTime", ((int) Double.parseDouble(sportTime) / 1) * 60 + (int) ((Double.parseDouble(sportTime) % 1) * 100) + "");
        intent.putExtra("sportCor", sportCor);

        Log.i("蓝牙", "时间: " + sportTime);
        startActivity(intent);
        Log.i("jianbaopp", "退出1");
        finish();
    }

    //非正常停止
    public void stopSportError() {
        controller.write(bluDataUtil.startStop("0"));         //停止，由运动状态到停止状态
//        video.stop();
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
        //跳转到结果页面
        intent = new Intent(VedioActivity.this, FinishSportActivity.class);
        intent.putExtra("sportDis", sportDis);
        intent.putExtra("sportTime", ((int) Double.parseDouble(sportTime) / 1) * 60 + (int) ((Double.parseDouble(sportTime) % 1) * 100) + "");
        intent.putExtra("sportCor", sportCor);

        Log.i("蓝牙", "时间: " + sportTime);

        x.postDelayed(new goToFinishActivity(), 2000);

    }

    Intent intent;

    class goToFinishActivity implements Runnable {
        public void run() {
            startActivity(intent);
            Log.i("jianbaopp", "退出2");
            finish();
        }
    }

    /**
     * 开始运动
     */
    public void startSport() {
        controller.write(bluDataUtil.startStop("1"));         //启动 ，停止待机状态到开始运动
    }

    public void exceptionCode(String str) {
        if (TextUtils.isEmpty(str)) {
            ex_layout.setVisibility(View.GONE);
            ex_tv.setText("");
        } else {
            ex_layout.setVisibility(View.VISIBLE);
            ex_tv.setText(str);
        }
    }

    public void initBle() {
        //注册广播
        receiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConstantUtils.ACTION_RECEIVE_MESSAGE_FROM_DEVICE);
        intentFilter.addAction(ConstantUtils.ACTION_STOP_CONNECT);
        registerReceiver(receiver, intentFilter);
    }


    public void onSetSpeed(int n) {

        if (n > 0) {
            if (now_speed < 1) {
                now_speed = 1;
            } else if (now_speed + 1 >= max_speed) {
                now_speed = max_speed;
                Toast.makeText(VedioActivity.this, "您不能超过最大速度!", Toast.LENGTH_SHORT).show();
            } else {
                now_speed = (float) (now_speed + 0.5);
            }
        } else {
            if (now_speed - 1 <= 1) {
                now_speed = min_speed;
                Toast.makeText(VedioActivity.this, "您不能低于最小速度!", Toast.LENGTH_SHORT).show();
            } else {
                now_speed = (float) (now_speed - 0.5);
            }
        }

        Log.i("蓝牙蓝牙", decimalFormat.format(now_speed) + "-------");
        controller.write(bluDataUtil.addSpeed(decimalFormat.format(now_speed)));  //速度调节
    }

//    @Override
//    public void onSetSpeedNoSlope(int n) {
//        if (n > 0) {
//            if (now_speed < 1) {
//                now_speed = 1;
//            } else if (now_speed + 1 >= max_speed) {
//                now_speed = max_speed;
//                Toast.makeText(VedioActivity.this, "您不能超过最大速度!", Toast.LENGTH_SHORT).show();
//            } else {
//                now_speed = (int) now_speed + 1;
//            }
//        } else {
//            if (now_speed - 1 <= min_speed) {
//                now_speed = min_speed;
//                Toast.makeText(VedioActivity.this, "您不能低于最小速度!", Toast.LENGTH_SHORT).show();
//            } else {
//                now_speed = (int) now_speed - 1;
//            }
//        }
//
//        controller.write(bluDataUtil.addSpeed(decimalFormat.format(now_speed)));  //速度调节
//    }
//
//    @Override
//    public void onSetSLope(int n) {
//        if (slopeFlag) {     //当存在坡度调节
//            if (n > 0) {
//                if (now_slope + 1 >= max_slope) {
//                    now_slope = max_slope;
//                    Toast.makeText(VedioActivity.this, "您不能超过最大坡度!", Toast.LENGTH_SHORT).show();
//                } else {
//                    now_slope = now_slope + 1;
//                }
//            } else {
//                if (now_slope - 1 <= 0) {
//                    now_slope = 0;
//                } else {
//                    now_slope = now_slope - 1;
//                }
//            }
//            controller.write(bluDataUtil.addSlope(String.valueOf(now_slope)));   //坡度减少
//        } else {     //当不存在坡度调节
//            if (n > 0) {
//                if (now_speed < 1) {
//                    now_speed = 1;
//                } else if (now_speed + 1 >= max_speed) {
//                    now_speed = max_speed;
//                    Toast.makeText(VedioActivity.this, "您不能超过最大速度!", Toast.LENGTH_SHORT).show();
//                } else {
//                    now_speed = (int) now_speed + 1;
//                }
//            } else {
//                if (now_speed - 1 <= min_speed) {
//                    now_speed = min_speed;
//                    Toast.makeText(VedioActivity.this, "您不能低于最小速度!", Toast.LENGTH_SHORT).show();
//                } else {
//                    now_speed = (int) now_speed - 1;
//                }
//            }
//            controller.write(bluDataUtil.addSpeed(decimalFormat.format(now_speed)));  //速度调节
//        }
//    }

    /**
     * 接收广播，接收蓝牙模块发过来的值
     */
    public class MsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equalsIgnoreCase(ConstantUtils.ACTION_STOP_CONNECT)) {
                Log.i("蓝牙", "连接已断开");
                stopSport();
            } else if (intent.getAction().equalsIgnoreCase(ConstantUtils.ACTION_RECEIVE_MESSAGE_FROM_DEVICE)) {
                //receivedMessage.append(u.toStringHex(intent.getStringExtra("message")).trim());
                //Log.i("蓝牙数据", u.toStringHex(intent.getStringExtra("message")).trim());
                try {
                    bluResult = bluDataUtil.SplitStr(u.toStringHex(intent.getStringExtra("message")).trim(), context);
                    if (bluResult != null) {
                        if (bluResult.code.equals("0")) {
                            bluResult.speed = String.format("%.2f", (Float.valueOf(bluResult.speed) ));
                            bluResult.distance = String.format("%.2f", (Float.valueOf(bluResult.distance)));

                            now_speed = Float.parseFloat(bluResult.speed);
                            now_slope = Integer.parseInt(bluResult.slope);              //坡度
                            max_speed = 6;
                            min_speed = Float.parseFloat(bluResult.minSpeed);
                            max_slope = Integer.parseInt(bluResult.maxSlope);
                            slopeFlag = isFlag(bluResult.slopeFlag);
                            bluState = Integer.parseInt(bluResult.state);
                            Log.i("蓝牙", "----------" + slopeFlag + "=" + bluResult.slopeFlag + "--------min_speed=" + min_speed);
                            sportDis = Double.parseDouble(bluResult.distance);
                            sportCor = Integer.parseInt(bluResult.calories);
                            sportTime = bluResult.time;
                            //Log.i("蓝牙数据", bluState+"=----------");
                            updateView(bluResult);
                        } else if (bluResult.code.equals("1")) {
                            exceptionCode("E01");
                            stopSportError();
                        } else if (bluResult.code.equals("2")) {
                            exceptionCode("E02");
                            stopSportError();
                        } else if (bluResult.code.equals("3")) {
                            exceptionCode("E03");
                            stopSportError();
                        } else if (bluResult.code.equals("4")) {
                            exceptionCode("E04");
                            stopSportError();
                        } else if (bluResult.code.equals("5")) {
                            exceptionCode("E05");
                            stopSportError();
                        } else if (bluResult.code.equals("6")) {
                            exceptionCode("E06");
                            stopSportError();
                        } else if (bluResult.code.equals("7")) {
                            exceptionCode("E07");
                            stopSportError();
                        }
                    }
                } catch (Exception e) {

                }
            }
        }
    }


    @Override
    protected void initView() {
//        video = new Video(VedioActivity.this);
//        video.onTouchSportListener(this);
//        sport_heart = (TextView) findViewById(R.id.sport_heart);
//        sport_time =(TextView) findViewById(R.id.sport_time);
//        sport_kcor =(TextView) findViewById(R.id.sport_kcor);
//        sport_dis = (TextView)findViewById(R.id.sport_dis);
//        sport_speed = (TextView)findViewById(R.id.sport_speed);
//        sport_speed.setOnClickListener(this);
//        sport_slope = (TextView)findViewById(R.id.sport_slope);
//        sport_slope.setOnClickListener(this);
//
//        yindao = (ImageView) findViewById(R.id.yindao);
//        yindao.setOnClickListener(this);
//
//        two = (TextView) findViewById(R.id.two);
//        two.setOnClickListener(this);
//        four = (TextView) findViewById(R.id.four);
//        four.setOnClickListener(this);
//        six = (TextView) findViewById(R.id.six);
//        six.setOnClickListener(this);
//        eight = (TextView) findViewById(R.id.eight);
//        eight.setOnClickListener(this);
//        ten = (TextView) findViewById(R.id.ten);
//        ten.setOnClickListener(this);
//        travel = (TextView) findViewById(R.id.travel);
//        travel.setOnClickListener(this);
//
//        btnText =(TextView) findViewById(R.id.btnText);
//        stopBtn =(ImageButton) findViewById(R.id.stopBtn);
//        stopBtn.setOnClickListener(this);
//
//        kuaijieLayout = (LinearLayout) findViewById(R.id.kuaijieLayout);
//
//        ex_layout = (RelativeLayout) findViewById(R.id.ex_layout);
//        ex_tv = (TextView) findViewById(R.id.ex_tv);
    }

    public String getTime(String str) {
        String miao = "0";

        if ((int) ((Double.parseDouble(str) % 1) * 100) < 10) {
            miao = "0" + (int) ((Double.parseDouble(str) % 1) * 100);
        } else {
            miao = (int) ((Double.parseDouble(str) % 1) * 100) + "";
        }

        return ((int) Double.parseDouble(str) / 1) + ":" + miao;
    }

    public void updateView(BluResult bluResult) {
//        sport_heart.setText(bluResult.heart);
//        sport_time.setText(getTime(bluResult.time));
//        sport_kcor.setText(bluResult.calories + "Kcal");
//        sport_dis.setText(bluResult.distance + "km");
//        sport_speed.setText(bluResult.speed);
//        sport_slope.setText(bluResult.slope + "");
//
        tv_time.setText(getTime(bluResult.time));
        tv_speed.setText(bluResult.speed + "MPH");
        tv_k.setText(bluResult.calories + "Kcal");
        tv_mileage.setText(bluResult.distance + getString(R.string.unit));
//        if (!slopeFlag) {
//            sport_slope.setClickable(false);
//        }

        if (Double.parseDouble(bluResult.speed) >= Double.parseDouble(bluResult.minSpeed)) {
            isStop = true;
        }/*else if(isStop && Double.parseDouble(bluResult.speed) < Double.parseDouble(bluResult.minSpeed)){
            isStop = false;
            Log.i("蓝牙","退出3");
            stopSport();
        }*/
        if (dataNum != 0) {
            if ("time".equals(model)) {
                Log.i("蓝牙", "model = " + model + "   dataNum = " + dataNum);
                if (Double.parseDouble(sportTime) >= dataNum) {
                    if (!flag) {
                        Log.i("蓝牙", "退出4");
                        stopSport();
                    }
                    flag = true;
                    toastLog("今日目标完成");

                }
            } else if ("cor".equals(model)) {
                if (sportCor >= dataNum) {
                    if (!flag) {
                        Log.i("蓝牙", "退出5");
                        stopSport();
                    }
                    flag = true;
                    toastLog("今日目标完成");
                }
            } else if ("dis".equals(model)) {
                if (sportDis >= dataNum) {
                    if (!flag) {
                        Log.i("蓝牙", "退出6");
                        stopSport();
                    }
                    flag = true;
                    toastLog("今日目标完成");
                }
            }
        }

        if (bluState == 60) {
            // stopBtn.setText("启动");
            exceptionCode(getResources().getString(R.string.noSalf));
            Log.i("蓝牙", "退出8");
            stopSport();
        } else if (bluState == 10) {
            iv_player.setText(R.string.startRun);


        } else {
            iv_player.setText(R.string.stop);
            exceptionCode("");
        }
        //stopBtn.setText("状态:" + bluState);
    }

    @Override
    protected void initData() {

    }

//    @Override
//    public void onSufaceClick() {
//        if (kuaijieLayout.getVisibility() == View.VISIBLE) {
//            kuaijieLayout.setVisibility(View.GONE);
//        }
//    }

    int n = 0;  //n = 1  为速度调节   n = 2  为坡度调节


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();

        /**
         * 设置为横屏
         */

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        video.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    /**
     * 获取是否为某种模式下的跑步
     */
    public void getModel() {
        if ("true".equals(aCache.getAsString("modelboolean"))) {
            String daonum = aCache.getAsString("daonum");
            dataNum = Integer.parseInt(daonum);
            model = aCache.getAsString("model");
        } else {
            model = "";
        }
    }

    public boolean isFlag(String str) {
        if ("1".equals(str)) {
            return true;
        } else {
            return false;
        }
    }
}
